import PySimpleGUI as sg
import cv2
import numpy as np
import vlc
from sys import platform as PLATFORM

#------- GUI definition & setup --------#

sg.theme('DarkBlue')

gui_font='Any 18'
character_size=(7,1)


def btn(name):  # a PySimpleGUI "User Defined Element" (see docs)
    return sg.Button(name, size=(6, 1), pad=(1, 1))

# col1=sg.Column([[sg.Input(default_text='kaluli.flv',key='-VIDEO_LOCATION-'), sg.Button('load')],
#                 [sg.Image('', size=(300, 170), key='-VID_OUT-')],
#                 ])


col2 = sg.Column([[sg.Image(filename='', key='image')],
                  [sg.Text('垃圾种类', font=gui_font),
                   sg.Text('具体垃圾', font=gui_font,size=character_size),
                   sg.Text('垃圾数量', font=gui_font),
                   sg.Text('满载状态', font=gui_font)],
                  [sg.Text('可回收物', font=gui_font),
                   sg.Text('具体垃圾', key='gar1', font=gui_font,size=character_size),
                   sg.Text('0', font=gui_font,size=character_size),
                   sg.Button(' ',key='gar0_status',button_color=('red','green'))],
                  [sg.Text('厨余垃圾', font=gui_font),
                   sg.Text('具体垃圾', key='gar2', font=gui_font,size=character_size),
                   sg.Text('0', font=gui_font,size=character_size),
                   sg.Button(' ',key='gar1_status',button_color=('red','green'))],
                  [sg.Text('其他垃圾', font=gui_font),
                   sg.Text('具体垃圾', key='gar3', font=gui_font,size=character_size),
                   sg.Text('0', font=gui_font,size=character_size),
                   sg.Button(' ',key='gar2_status',button_color=('red','green'))],
                  [sg.Text('有害垃圾', font=gui_font),
                   sg.Text('具体垃圾', key='gar4', font=gui_font,size=character_size),
                   sg.Text('0', font=gui_font,size=character_size),
                   sg.Button(' ',key='gar3_status',button_color=('red','green'))],
                  ])

layout = [[sg.Input(default_text='kaluli.flv', key='-VIDEO_LOCATION-'), sg.Button('load')],
          [sg.Image('', size=(300, 170), key='-VID_OUT-'), col2],
          [btn('previous'), btn('play'), btn('next'), btn('pause'),
           btn('stop'), btn('Record'), btn('Stop'), btn('Exit')],
          [sg.Text('Load media to start', key='-MESSAGE_AREA-')]]

window = sg.Window('Garbage Detect', layout,
                   element_justification='center', finalize=True, resizable=True)

window['-VID_OUT-'].expand(True, True)                # type: sg.Element
# window.Maximize()
#------------ Media Player Setup ---------#

inst = vlc.Instance()
list_player = inst.media_list_player_new()
media_list = inst.media_list_new([])
list_player.set_media_list(media_list)
player = list_player.get_media_player()
if PLATFORM.startswith('linux'):
    player.set_xwindow(window['-VID_OUT-'].Widget.winfo_id())
else:
    player.set_hwnd(window['-VID_OUT-'].Widget.winfo_id())
# cap = cv2.VideoCapture(0)

recording = False
#------------ The Event Loop ------------#
def gui_scan():
    global recording
    # run with a timeout so that current location can be updated
    event, values = window.read(timeout=20)
    if event == 'Exit' or event == sg.WIN_CLOSED:
        window.close()
        return 3
    elif event == 'Record':
        recording = True
        return 1

    elif event == 'Stop':
        recording = False
        return 2
        img = np.full((300, 170), 255)
        # this is faster, shorter and needs less includes
        imgbytes = cv2.imencode('.png', img)[1].tobytes()
        window['image'].update(data=imgbytes)

    if event == sg.WIN_CLOSED:
        return 3

    if event == 'play':
        list_player.play()
    if event == 'pause':
        list_player.pause()
    if event == 'stop':
        list_player.stop()
    if event == 'next':
        list_player.next()
        list_player.play()
    if event == 'previous':
        list_player.previous()      # first call causes current video to start over
        list_player.previous()      # second call moves back 1 video from current
        list_player.play()
    if event == 'load':
        if values['-VIDEO_LOCATION-'] and not 'Video URL' in values['-VIDEO_LOCATION-']:
            media_list.add_media(values['-VIDEO_LOCATION-'])
            list_player.set_media_list(media_list)
            # only add a legit submit
            window['-VIDEO_LOCATION-'].update('Video URL or Local Path:')

    # update elapsed time if there is a video loaded and the player is playing
    if player.is_playing():
        window['-MESSAGE_AREA-'].update("{:02d}:{:02d} / {:02d}:{:02d}".format(*divmod(player.get_time()//1000, 60),
                                                                               *divmod(player.get_length()//1000, 60)))
    else:
        window['-MESSAGE_AREA-'].update(
            'Load media to start' if media_list.count() == 0 else 'Ready to play media')

def gui_update(image):
    if recording:
        imgbytes = cv2.imencode('.png', image)[1].tobytes()  # ditto
        window['image'].update(data=imgbytes)

def alarm_sign_stop():
    window['gar0_status'].update(button_color=('red','green'))
    window['gar1_status'].update(button_color=('red','green'))
    window['gar2_status'].update(button_color=('red','green'))
    window['gar3_status'].update(button_color=('red','green'))

